package com.me.study.javaCore.dynamicProxy.cglib;

import com.me.common.util.CglibProxyUtil;
import java.lang.reflect.Method;

import com.me.study.javaCore.dynamicProxy.TargetImpl;
import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.CallbackFilter;
import net.sf.cglib.proxy.NoOp;
import org.junit.Test;

/**
 * CGLIB 测试类
 *
 * @author ME
 * @date   2019/2/27 15:49
 */
public class TestCglib {

    @Test
    public void testCglib() {
        // 保存 Cglib生成的class文件: H:\kotlinSpace\testME\testJDK8\net\sf\cglib
        // System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "H:\\kotlinSpace\\testME\\testJDK8\\cglibClass");

        CglibAdvice cglibAdvice = new CglibAdvice();

        // // 通过 CGLIB 创建目标对象（的子类）
        // Enhancer enhancer = new Enhancer();
        // enhancer.setSuperclass(TargetImpl.class);
        // enhancer.setCallback(aProxy);
        // TargetImpl target = (TargetImpl) enhancer.create();

        TargetImpl target = CglibProxyUtil
            .getProxy(TargetImpl.class, new Callback[]{cglibAdvice, NoOp.INSTANCE}, new CallbackFilter() {
                @Override
                public int accept(Method method) {
                    // 方法名为 doSome22 才执行索引为 0 的 Callback，也就是只拦截 doSome22()
                    if (method.getName().equals("doSome22")) {
                        return 0;
                    }
                    // 其他方法走 NoOp.INSTANCE，也就是不做增强
                    return 1;
                }
            });

        target.doSome(10);
        System.out.println();
        target.doSome22("Tomcat");
    }

    // public static void main(String[] args) {
    //     for (int i = 0; i < 100; i++) {
    //         Thread t = new Thread() {
    //             @Override
    //             public void run() {
    //                 CglibAdvice proxyT = new CglibAdvice();
    //                 TargetImpl target = proxyT.getProxy(TargetImpl.class);
    //                 target.doSome();
    //             }
    //         };
    //         t.start();
    //     }
    // }
}
